<template>
  <div class="department-container">
    <div class="app-container">

      <!-- 具体页面结构 -->
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>共{{ total }}条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <!-- *操作 -->
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-allow="'export'" type="danger" size="small" @click="handleDownload">导出excel</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </PageTools>
      <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
        <el-table-column label="序号" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像">
          <template #default="{row}">
            <img v-imgError="defaultImg" :src="row.staffPhoto" style="width: 100px; height: 100px;">
          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" sortable />
        <el-table-column label="聘用形式">
          <template #default="{row}">
            {{ getEmployeesEnum(row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" prop="timeOfEntry" sortable />
        <el-table-column label="操作" width="280">
          <template #default="{row}">
            <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> -->
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small" @click="hAssginRole(row.id)">分配角色</el-button>
            <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <el-row type="flex" justify="center" align="middle">
        <el-pagination
          :current-page="page"
          :page-sizes="[2, 5, 10, 50]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <el-dialog
        title="新增"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <EmpDialog
          ref="refDialog"
          @success="hSuccess"
          @close="showDialog=false"
        />
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="showRoleDialog">
        <AssignRole v-if="showRoleDialog" :cur-id="curId" @close="showRoleDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 导入api函数
import { getEmployeesList, delEmployee } from '@/api/employees'
import Img from '@/assets/common/head.jpg'
// 导入员工枚举
import employeesEnum from '@/constant/employees'
import EmpDialog from './empDialog'
import { EN_CN } from '@/utils/en-ch'
import AssignRole from './assignRole'
// const hireType = {}
// employeesEnum.hireType.forEach(item => { hireType[item.id] = item.value })
const hireType = employeesEnum.hireType.reduce((obj, item) => {
  obj[item.id] = item.value
  return obj
}, {})
// 默认导出
export default {
  components: {
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      page: 1, // 当前页码值
      size: 2, // 每页条数
      list: [], // 员工列表
      total: 0, // 总条数
      showDialog: false, // 控制弹框
      showRoleDialog: false,
      curId: '',
      defaultImg: Img
    }
  },
  // 初始化调用
  created() {
    this.loadEmployeesList()
  },
  methods: {
    hAssginRole(id) {
      this.curId = id
      this.showRoleDialog = true
    },
    // 导出excel
    async handleDownload() {
      try {
        const { data: res } = await getEmployeesList(this.page, this.size)
        // console.log('列表数据', res)
        // const excelData = EN_CN(res.rows)
        // console.log('excelData', excelData)

        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            ...EN_CN(res.rows),
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除
    async hDel(id) {
      try {
        await this.$confirm('你确定删除吗?')
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) this.page--
        if (this.page <= 0) this.page = 1
        this.loadEmployeesList()
      } catch (error) {
        console.log(error)
      }
    },
    // 关闭表单
    hClose() {
      this.$refs.refDialog.resetForm()
    },
    // 获取枚举数据
    getEmployeesEnum(id) {
      // return employeesEnum.hireType.find(item => item.id === id).value
      return hireType[id] || '未知'
    },
    // 分页控制
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.size = val
      this.loadEmployeesList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeesList()
    },
    // 获取员工列表
    async loadEmployeesList() {
      try {
        const res = await getEmployeesList(this.page, this.size)
        console.log('获取员工列表', res)
        this.total = res.data.total
        this.list = res.data.rows
      } catch (error) {
        console.log(error)
      }
    },
    // 新增员工
    hAdd() {
      this.showDialog = true
    },
    // 成功的回调
    hSuccess() {
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeesList()
    }
  }
}
</script>
